<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.children.length == 0">无权限</el-tag>
            <el-row
              :class=" ['bdbottom', i1 == 0?'bdtop':'' ,'vconter'] "
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class=" [i2 == 0?'':'bdtop' ,'vconter'] "
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                      type="success"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag
                      @close="removeRightById(scope.row,item3.id)"
                      closable
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "rights",
  data() {
    return {
      //所有角色列表数据
      rolesList: [],

      //控制分配权限对话框
      setRightDialogVisible: false,

      //权限的列表
      rightsList: [],
      // 树形结构规则
      treeProps: {
        label: "authName",
        children: "children"
      },
      //树形结构默认选中的节点
      defKeys: [],
      // 当前分配权限的id
      roleId:"",
    };
  },
  methods: {
    //获取权限列表
    async getRolesList() {
      var { data: res } = await this.$axios.get("roles");
      if (res.meta.status != 200) {
        this.$message.error("获取角色列表失败");
        return;
      }
      this.rolesList = res.data;
    },
    //删除权限
    async removeRightById(row, id) {
      const confirmResult = await this.$confirm("确认删除权限？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      if (confirmResult != "confirm") {
        this.$message.info("已取消删除");
        return;
      }
      const { data: res } = await this.$axios.delete(
        `roles/${row.id}/rights/${id}`
      );
      if (res.meta.status != 200) {
        this.$message.error("删除失败");
        return;
      }
      this.$message.success("删除成功");

      //这里不建议重新获取角色列表
      // this.getRolesList();

      //建议只改里面的 不刷新整个框架 把返回的数据直接赋值
      row.children = res.data;
    },
    //分配权限
    async showSetRightDialog(row) {
      // 为下面分配存一个索引id
      this.roleId = row.id

      const { data: res } = await this.$axios.get("rights/tree");
      if (res.meta.status != 200) {
        return;
      }
      this.rightsList = res.data;

      //递归获取节点
      this.getLeafKeys(row, this.defKeys);

      this.setRightDialogVisible = true;
    },
    //通过递归，获取角色下所有三级权限的id，并保存到defkeys数组中
    getLeafKeys(node, arr) {
      //如果节点不包含children，则为三级节点
      if (!node.children) {
        arr.push(node.id);
        return;
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      });
    },
    //对话框关闭
    setRightDialogClosed() {
      this.defKeys = [];
    },
    //分配权限确认
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      //拼接为字符串
      const idStr = keys.join(',');
      const {data:res} = await this.$axios.post(`roles/${this.roleId}/rights`,{
        rids:idStr
      })

      if(res.meta.status != 200){
        this.$message.error('分配权限失败!');
        return
      }
      this.getRolesList();
      this.setRightDialogVisible = false;
    }
  },
  created() {
    this.getRolesList();
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vconter {
  display: flex;
  align-items: center;
}
</style>